import React, { useState, useEffect, useRef, useCallback } from 'react'
import { useChatStore, Session } from '../stores/chatStore'
import { Button, IconButton } from './ui/Button'
import { SessionGroup } from './ui/SessionGroup'
import { groupSessionsByTime } from '../utils/timeGrouping'
import { PlusIcon, SearchIcon, MessageCircleIcon, SettingsIcon } from './ui/Icon'
import { EmptySessionState, EmptySearchState } from './ui/Onboarding'
import { debounce } from '../utils/debounce'

interface SessionListProps {
  className?: string
  onSessionSelect?: () => void
}

export const SessionList: React.FC<SessionListProps> = ({ className, onSessionSelect }) => {
  const { 
    sessions, 
    currentSession, 
    pagination,
    filters,
    isLoading,
    loadSessions,
    searchSessions,
    loadMoreSessions,
    createSession, 
    renameSession,
    deleteSession, 
    setCurrentSession,
    toggleFavoriteSession,
    toggleArchiveSession,
    updateFilters
  } = useChatStore()
  
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editTitle, setEditTitle] = useState('')
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(null)
  
  // 滚动容器引用
  const scrollContainerRef = useRef<HTMLDivElement>(null)
  const searchInputRef = useRef<HTMLInputElement>(null)
  
  // 选中会话索引（用于键盘导航）
  const [selectedIndex, setSelectedIndex] = useState<number>(-1)

  // 初始化加载会话
  useEffect(() => {
    loadSessions()
  }, [])

  // 键盘快捷键处理
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Ctrl/Cmd + K: 快速搜索
      if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault()
        searchInputRef.current?.focus()
        return
      }

      // Ctrl/Cmd + N: 新建会话
      if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
        e.preventDefault()
        handleNewSession()
        return
      }

      // F2: 重命名当前会话
      if (e.key === 'F2' && currentSession) {
        e.preventDefault()
        startEdit(currentSession)
        return
      }

      // 上下箭头: 切换会话选择
      if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
        e.preventDefault()
        const direction = e.key === 'ArrowUp' ? -1 : 1
        const newIndex = Math.max(0, Math.min(sessions.length - 1, selectedIndex + direction))
        setSelectedIndex(newIndex)
        
        if (sessions[newIndex]) {
          setCurrentSession(sessions[newIndex])
        }
        return
      }

      // Enter: 选择当前高亮会话
      if (e.key === 'Enter' && selectedIndex >= 0 && sessions[selectedIndex]) {
        setCurrentSession(sessions[selectedIndex])
        onSessionSelect?.()
        return
      }
    }

    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [selectedIndex, sessions, currentSession, handleNewSession, startEdit, setCurrentSession, onSessionSelect])

  // 更新选中索引当会话变化时
  useEffect(() => {
    if (currentSession && sessions.length > 0) {
      const index = sessions.findIndex(s => s.id === currentSession.id)
      if (index >= 0) {
        setSelectedIndex(index)
      }
    }
  }, [currentSession, sessions])

  // 无限滚动处理
  const handleScroll = useCallback((e: React.UIEvent<HTMLDivElement>) => {
    const { scrollTop, scrollHeight, clientHeight } = e.currentTarget
    // 滚动到底部100px时自动触发加载
    if (scrollHeight - scrollTop - clientHeight < 100) {
      if (!isLoading && pagination.page < pagination.totalPages) {
        loadMoreSessions()
      }
    }
  }, [isLoading, pagination, loadMoreSessions])

  // 防抖搜索处理
  const debouncedSearch = useCallback(
    debounce((query: string) => {
      searchSessions(query)
    }, 300),
    [searchSessions]
  )

  // 筛选和分组会话 - 现在服务端已经处理了筛选和排序
  const favoritesSessions = sessions.filter(session => session.is_favorite)
  const regularSessions = sessions.filter(session => !session.is_favorite)
  
  const sessionGroups = [
    // 如果有收藏会话，单独显示一个收藏分组
    ...(favoritesSessions.length > 0 ? [{
      key: 'favorites',
      label: '收藏会话',
      icon: '⭐',
      sessions: favoritesSessions
    }] : []),
    // 然后显示按时间分组的普通会话
    ...groupSessionsByTime(regularSessions)
  ]

  // 格式化时间
  const formatTime = (date: Date) => {
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (minutes < 1) return '刚刚'
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    return date.toLocaleDateString()
  }

  // 创建新会话
  const handleNewSession = async () => {
    try {
      await createSession()
    } catch (error) {
      console.error('创建会话失败:', error)
    }
  }

  // 搜索处理 - 使用防抖
  const handleSearch = (query: string) => {
    debouncedSearch(query)
  }

  // 开始编辑
  const startEdit = (session: Session) => {
    setEditingId(session.id)
    setEditTitle(session.title)
  }

  // 保存编辑
  const saveEdit = async () => {
    if (editingId && editTitle.trim()) {
      try {
        await renameSession(editingId, editTitle.trim())
        setEditingId(null)
        setEditTitle('')
      } catch (error) {
        console.error('重命名失败:', error)
      }
    }
  }

  // 取消编辑
  const cancelEdit = () => {
    setEditingId(null)
    setEditTitle('')
  }

  // 删除会话
  // 删除会话
  const handleDelete = async (sessionId: string) => {
    try {
      await deleteSession(sessionId)
      setShowDeleteConfirm(null)
    } catch (error) {
      console.error('删除失败:', error)
    }
  }

  // 筛选器处理
  const handleFilterChange = async (filter: 'favorite' | 'archived' | '') => {
    await updateFilters({ filter })
  }

  // 排序处理
  const handleSortChange = async (sort: 'lastActiveAt' | 'title' | 'created_at', order: 'asc' | 'desc') => {
    await updateFilters({ sort, order })
  }

  return (
    <div className={`bg-white border-r flex flex-col ${className}`} style={{ borderColor: 'var(--gray-200)' }}>
      {/* 头部：搜索和新建按钮 */}
      <div className="p-5 border-b" style={{ borderColor: 'var(--gray-200)', background: 'var(--gray-50)' }}>
        <button
          onClick={handleNewSession}
          disabled={isLoading}
          className="w-full flex items-center justify-center gap-2 px-4 py-3 rounded-xl text-white font-medium hover:scale-[1.02] transition-all disabled:opacity-50"
          style={{
            background: 'var(--primary-500)',
            borderRadius: 'var(--radius-lg)',
            fontSize: 'var(--text-sm)'
          }}
          onMouseEnter={(e) => {
            if (!isLoading) {
              e.currentTarget.style.background = 'var(--primary-600)'
            }
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.background = 'var(--primary-500)'
          }}
        >
          {isLoading ? (
            <div className="flex gap-1">
              <div className="w-2 h-2 rounded-full bg-white animate-bounce" style={{ animationDelay: '0ms' }}></div>
              <div className="w-2 h-2 rounded-full bg-white animate-bounce" style={{ animationDelay: '150ms' }}></div>
              <div className="w-2 h-2 rounded-full bg-white animate-bounce" style={{ animationDelay: '300ms' }}></div>
            </div>
          ) : (
            <>
              <span>➕</span>
              新对话
            </>
          )}
        </button>
        
        <div className="relative mt-4">
          <div className="absolute left-3 top-3 text-gray-400">
            🔍
          </div>
          <input
            ref={searchInputRef}
            type="text"
            placeholder="搜索会话... (Ctrl+K)"
            value={filters.query}
            onChange={(e) => handleSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2.5 border-2 bg-white outline-none transition-all"
            style={{
              border: '2px solid var(--gray-200)',
              borderRadius: 'var(--radius-lg)',
              fontSize: 'var(--text-sm)'
            }}
            onFocus={(e) => {
              e.currentTarget.style.borderColor = 'var(--primary-500)'
            }}
            onBlur={(e) => {
              e.currentTarget.style.borderColor = 'var(--gray-200)'
            }}
          />
        </div>
        
        {/* 筛选器和排序控件 */}
        <div className="mt-3 flex items-center justify-between gap-2">
          {/* 筛选器 */}
          <div className="flex items-center gap-1">
            <button
              onClick={() => handleFilterChange('')}
              className={`px-3 py-1 text-xs rounded-full transition-colors ${
                filters.filter === '' 
                  ? 'bg-blue-100 text-blue-700 font-medium' 
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              全部
            </button>
            <button
              onClick={() => handleFilterChange('favorite')}
              className={`px-3 py-1 text-xs rounded-full transition-colors ${
                filters.filter === 'favorite' 
                  ? 'bg-yellow-100 text-yellow-700 font-medium' 
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              ⭐ 收藏
            </button>
            <button
              onClick={() => handleFilterChange('archived')}
              className={`px-3 py-1 text-xs rounded-full transition-colors ${
                filters.filter === 'archived' 
                  ? 'bg-gray-200 text-gray-700 font-medium' 
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              📦 归档
            </button>
          </div>
          
          {/* 排序器 */}
          <div className="flex items-center">
            <select
              value={`${filters.sort}-${filters.order}`}
              onChange={(e) => {
                const [sort, order] = e.target.value.split('-') as ['lastActiveAt' | 'title' | 'created_at', 'asc' | 'desc']
                handleSortChange(sort, order)
              }}
              className="text-xs bg-transparent border-none outline-none cursor-pointer text-gray-600 hover:text-gray-900"
            >
              <option value="lastActiveAt-desc">最近活跃</option>
              <option value="created_at-desc">最新创建</option>
              <option value="title-asc">名称 A-Z</option>
              <option value="title-desc">名称 Z-A</option>
            </select>
          </div>
        </div>
      </div>

      {/* 分组会话列表 */}
      <div 
        ref={scrollContainerRef}
        className="flex-1 overflow-y-auto py-3 custom-scrollbar"
        onScroll={handleScroll}
      >
        {isLoading && sessions.length === 0 ? (
          <div className="flex items-center justify-center h-32">
            <div className="flex gap-1">
              <div className="w-2 h-2 rounded-full bg-blue-400 animate-bounce" style={{ animationDelay: '0ms' }}></div>
              <div className="w-2 h-2 rounded-full bg-blue-400 animate-bounce" style={{ animationDelay: '150ms' }}></div>
              <div className="w-2 h-2 rounded-full bg-blue-400 animate-bounce" style={{ animationDelay: '300ms' }}></div>
            </div>
          </div>
        ) : sessions.length === 0 ? (
          filters.query ? (
            <EmptySearchState 
              searchTerm={filters.query}
              onClearSearch={() => handleSearch('')}
            />
          ) : (
            <EmptySessionState onCreateSession={handleNewSession} />
          )
        ) : (
          <div className="px-3">
            {sessionGroups.map((group) => (
              <SessionGroup
                key={group.key}
                label={group.label}
                icon={group.icon}
                sessions={group.sessions}
                currentSessionId={currentSession?.id}
                onSessionSelect={(session) => {
                  setCurrentSession(session)
                  onSessionSelect?.()
                }}
                onSessionEdit={startEdit}
                onSessionDelete={handleDelete}
                onToggleFavorite={toggleFavoriteSession}
              />
            ))}
            
            {/* 无限滚动加载指示器 */}
            {isLoading && sessions.length > 0 && (
              <div className="mt-4 px-3">
                <div className="flex items-center justify-center py-4">
                  <div className="flex gap-1">
                    <div className="w-2 h-2 rounded-full bg-gray-400 animate-bounce" style={{ animationDelay: '0ms' }}></div>
                    <div className="w-2 h-2 rounded-full bg-gray-400 animate-bounce" style={{ animationDelay: '150ms' }}></div>
                    <div className="w-2 h-2 rounded-full bg-gray-400 animate-bounce" style={{ animationDelay: '300ms' }}></div>
                  </div>
                  <span className="ml-2 text-sm text-gray-500">加载中...</span>
                </div>
              </div>
            )}
            
            {/* 已加载完毕提示 */}
            {!isLoading && sessions.length > 0 && pagination.page >= pagination.totalPages && (
              <div className="mt-4 px-3">
                <div className="text-center py-2 text-xs text-gray-400">
                  已加载全部 {pagination.total} 个会话
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* 编辑对话框 */}
      {editingId && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white p-6 max-w-md w-full mx-4" style={{
            borderRadius: 'var(--radius-xl)',
            boxShadow: 'var(--shadow-lg)'
          }}>
            <h3 style={{ fontSize: 'var(--text-lg)', fontWeight: 600, marginBottom: '16px' }}>重命名会话</h3>
            <input
              type="text"
              value={editTitle}
              onChange={(e) => setEditTitle(e.target.value)}
              className="w-full px-4 py-3 border-2 outline-none transition-all"
              style={{
                border: '2px solid var(--gray-200)',
                borderRadius: 'var(--radius-lg)',
                fontSize: 'var(--text-base)'
              }}
              placeholder="输入会话名称"
              autoFocus
              onFocus={(e) => {
                e.currentTarget.style.borderColor = 'var(--primary-500)'
              }}
              onBlur={(e) => {
                e.currentTarget.style.borderColor = 'var(--gray-200)'
              }}
              onKeyDown={(e) => {
                if (e.key === 'Enter') saveEdit()
                if (e.key === 'Escape') cancelEdit()
              }}
            />
            <div className="flex gap-3 justify-end mt-5">
              <button
                onClick={cancelEdit}
                className="px-4 py-2 border rounded-lg hover:bg-gray-50 transition-colors"
                style={{
                  border: '1px solid var(--gray-200)',
                  borderRadius: 'var(--radius-md)',
                  fontSize: 'var(--text-sm)'
                }}
              >
                取消
              </button>
              <button
                onClick={saveEdit}
                disabled={!editTitle.trim()}
                className="px-4 py-2 text-white rounded-lg hover:scale-[1.02] transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                style={{
                  background: 'var(--primary-500)',
                  borderRadius: 'var(--radius-md)',
                  fontSize: 'var(--text-sm)'
                }}
                onMouseEnter={(e) => {
                  if (!e.currentTarget.disabled) {
                    e.currentTarget.style.background = 'var(--primary-600)'
                  }
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.background = 'var(--primary-500)'
                }}
              >
                保存
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 底部导航 */}
      <div className="border-t p-4" style={{ borderColor: 'var(--gray-200)', background: 'var(--gray-50)' }}>
        <div className="space-y-3">
          <button className="w-full flex items-center gap-3 px-3 py-2.5 text-gray-600 hover:text-gray-900 hover:bg-white rounded-lg transition-all" style={{
            borderRadius: 'var(--radius-md)',
            fontSize: 'var(--text-sm)'
          }}>
            <span>⚙️</span>
            <span>设置</span>
          </button>
          
          <div style={{ fontSize: 'var(--text-xs)', color: 'var(--gray-500)' }} className="px-3 space-y-1">
            <div>
              共 {pagination.total} 个会话
              {filters.query && ` · 显示 ${sessions.length} 个结果`}
            </div>
            <div className="text-gray-400">
              快捷键: ⌘K 搜索 • ⌘N 新建 • F2 重命名
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

